<?php

class Sondage_GsondageController extends Zend_Controller_Action
{

    public function init()
    {
    	
    	
        /* Initialize action controller here */
    	parent::init();
    	if (Zend_Auth::getInstance()->hasIdentity()) {
    		echo "already logged in as: " ;//. Zend_Auth::getInstance()->getIdentity();
    		$identity=Zend_Auth::getInstance()->getIdentity();
    		
    		/* Initialize action controller here */
    		if($identity->role!="admin"){
    			$this->_helper->redirector('login',"authentification","sondage");
    		}
    	}else{
    		$this->_helper->redirector('authentification','gparticipants','sondage');
    	}
    	 
    }

    public function indexAction()
    {
        // action body
    }

    public function addsondageAction()
    {
        // action body
        
    	$sondageform = new Application_Form_Addsondage();
    	$this->view->form = $sondageform;
    	 
    	if ($this->_request->isPost()) {
    		$formData = $this->_request->getPost();
    		if ($sondageform->isValid($formData)) {
    			$sondage = new Application_Model_DbTable_Sondage();
    		
    			$datestamp=new Zend_Date();
    			
    			$row = $sondage->createRow();
    			 
    			$identity=Zend_Auth::getInstance()->getIdentity();
    			
    			$row->sondagepersonne_idsondagepersonne = $identity->idsondagepersonne;
    			
    			$row->titre = $sondageform->getValue('titre');
    			$row->activation = $sondageform->getValue('activation');
    			$row->description = $sondageform->getValue('description');
    			$row->date_creation = $datestamp->get(zend_date::TIMESTAMP);
    			
    			 
    			
    			$row->date_publication = $datestamp->get(zend_date::TIMESTAMP);
    			
    			$row->domaine_iddomaine = $sondageform->getValue('domaine_iddomaine');
    			
    			
    			$result = $row->save();
    		
    			 
    			$this->_helper->redirector("gestionsondage");
    		}
    		 
    	}
    	
    	
    	
    	
    }

    public function sondageAction()
    {
        // action body
    }

    public function gestionsondageAction()
    {
        // action body
        
    	//chargement des donnée de la base de donnée
    	$mapper = new Application_Model_Mapper_Sondage();
    	     	 
    	$select=$mapper->fetchAllToArray();
    	//ajouter le requtte a la paginateur
    	$paginator = Zend_Paginator::factory($select);
    	//ajouter le nombre d'enregistrement par page
    	$paginator->setItemCountPerPage(3);
    	//ajouter la page par defaut
    	$paginator->setCurrentPageNumber($this->_getParam('page', 1));
    	//ajouter le paginateur au view
    	$this->view->paginator = $paginator;
    	
    	
    	$headercolums=array(
    			"titre"=> "Titre",
    			"domaine_iddomaine"=>"Domaine",
    			"date_creation"=>"date de création",
    			"date_publication"=>"date de publication"
    			
    			);
   $this->view->headercolums=$headercolums;
    	
    	Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
    	
    }

    public function editerquestionAction()
    {
        // action body
        
    	
    	
    	//chargement des donnée de la base de donnée
    	$mapper = new Application_Model_DbTable_Question();
    	 
    	$select=$mapper->fetchAll(array("sondage_idsondage = ?"=>$this->getRequest()->getParam("id")))->toArray();
    	//ajouter le requtte a la paginateur
    	 
    	
    	$paginator = Zend_Paginator::factory($select);
    	//ajouter le nombre d'enregistrement par page
    	$paginator->setItemCountPerPage(3);
    	//ajouter la page par defaut
    	$paginator->setCurrentPageNumber($this->_getParam('page', 1));
    	//ajouter le paginateur au view
    	$this->view->paginator = $paginator;
    	
    	
    	$headercolums=array(
    			"ordrequestion"=>"Ordre",
    			"textquestion"=> "Question",
    			"description"=>"Description",
    			"score"=>"Nombre de reponse juste"
    	
    	);
    	$this->view->headercolums=$headercolums;
    	
    	Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
    	
    	//********************************************Ajouter et enregistrer*****************
    	
    	$questionform = new Application_Form_Editerquestions();
    	$this->view->form = $questionform;
    	
    	 
    	
    	if($this->_request->getParam("idquestion")){
    		$datestamp=new Zend_Date();
    		$model=new Application_Model_DbTable_Question();
    		$data=$model->fetchRow('idQuestion =' . $this->_request->getParam("idquestion"))->toArray();
    	 
    		$datapopulate=array(
    	
    				'typequestion_idtypequestion'=>$data['typequestion_idtypequestion']
    				,'description'=>$data['description']
    				,'textquestion'=> $data['textquestion']
    				,'ordrequestion'=>$data['ordrequestion']
    				,'score'=>$data['score']
    					
    		);
    		$questionform->populate($datapopulate);
    	}
    	
    	
    	 
    	 
    	if ($this->_request->isPost()) {
    		$formData = $this->_request->getPost();
    		if ($questionform->isValid($formData)) {
    			$question = new Application_Model_DbTable_Question();
    			  
    			 
    			$data =array(
    					'sondage_idsondage'=>$this->getRequest()->getParam("id")
    					,'typequestion_idtypequestion'=>$questionform->getValue('typequestion_idtypequestion')
    					,'description'=>$questionform->getValue('description')
    					,'textquestion'=>$questionform->getValue('textquestion')
    					,'ordrequestion'=>$questionform->getValue('ordrequestion')
    					,'score'=>$questionform->getValue('score')
    						
    			);
    			if($this->_request->getParam("idquestion")){
    				$question->update($data,'idQuestion =' . $this->_request->getParam("idquestion"));
    			}else{
    				$question->insert($data);
    			}
    	 
    	
    			//	$questionform->reset();
    	
    			$this->_helper->redirector("editerquestion","gsondage","sondage",array("id"=>$this->getRequest()->getParam("id")));
    		}
    		 
    	}
    	
	
    }

    public function deletesondageAction()
    {
        // action body
        
        $id= $this->_request->getParam("id");
    	
        $participation = new Application_Model_DbTable_Participation();
        $participation->delete(" sondage_idsondage = $id ");
        
     
        $selector=$participation->select(Zend_Db_Table::SELECT_WITHOUT_FROM_PART);
        $selector->setIntegrityCheck(false);
        
        $selector->joinInner("question", " Question_idQuestion = idQuestion ");
       
        
        
        $reponse = new Application_Model_DbTable_Listesreponse();
        
        $selector=$reponse->select(Zend_Db_Table::SELECT_WITHOUT_FROM_PART);
        $selector->setIntegrityCheck(false);
        
        $selector->joinInner("question", " Question_idQuestion = idQuestion ");
        
        $selector->where(" sondage_idsondage = $id ");
        
      // $reponse->delete($selector);
        
        $reponse->getAdapter()->query($selector);
       
        $question = new Application_Model_DbTable_Question();
        $question->delete(" sondage_idsondage= $id ");
        
        
        
        $sondage = new Application_Model_DbTable_Sondage();
    	$sondage->delete(" idsondage = $id");
    	
    	$this->_helper->redirector("gestionsondage","gsondage","sondage");
    	 
    	
    	
    	
    }

    public function updatesondageAction()
    {
    	$form= new Application_Form_Addsondage();
    	$this->view->form=$form;
    	if($this->_request->getParam("id")){
    		$datestamp=new Zend_Date();
    		$model=new Application_Model_DbTable_Sondage();
    		$data=$model->fetchRow('idsondage =' . $this->_request->getParam("id"))->toArray();
    		
    		$date_creation = new Zend_Date($data['date_creation'], Zend_Date::TIMESTAMP);
    		$date_publication = new Zend_Date($data['date_publication'], Zend_Date::TIMESTAMP);
    		
    		$datapopulate=array(
    				
    				'titre'=>$data['titre']
    				,'description'=>$data['description']
    				,'date_creation'=> $date_creation->toString("dd-MM-YYYY")
    				,'date_publication'=>$date_publication->toString("dd-MM-YYYY")
    				,'domaine_iddomaine'=>$data['domaine_iddomaine']
    		  		,'activation'=>$data['activation']
    				 
    		);
    		$form->populate($datapopulate);
    	}
    	
    	
    	if ($this->_request->isPost()) {
    		$formData = $this->_request->getPost();
    		if ($form->isValid($formData)) {
    			$sondage = new Application_Model_DbTable_Sondage();
    	
    			$datestamp=new Zend_Date();
    			 
    			$row = $sondage->createRow();
    	
    			$identity=Zend_Auth::getInstance()->getIdentity();
    			
    			$date_creation = new Zend_Date($form->getValue('date_creation'));
    			$date_publication = new Zend_Date($form->getValue('date_publication'));
    			 
    			$data=array(
    			
    					'titre'=>$form->getValue('titre')
    					,'sondagepersonne_idsondagepersonne' => $identity->idsondagepersonne
    					,'description'=>$form->getValue('description')
    					,'date_creation'=> $date_creation->get(zend_date::TIMESTAMP)
    					,'date_publication'=>$date_publication->get(zend_date::TIMESTAMP)
    					,'domaine_iddomaine'=>$form->getValue('domaine_iddomaine')
    					,'activation'=>$form->getValue('activation')
    						
    			);
    			
    			$sondage->update($data, 'idsondage =' . $this->_request->getParam("id"));
    			 
    	
    			$this->_helper->redirector("gestionsondage");
    		}
    		 
    	}
    }

    public function editerrepenseAction()
    {
        // action body
        
    	//chargement des donnée de la base de donnée
    	$mapper = new Application_Model_DbTable_Reponse();
    	
    	$select=$mapper->fetchAll(array("Question_idQuestion = ?"=>$this->getRequest()->getParam("id")))->toArray();
    	//ajouter le requtte a la paginateur
    	
    	 
    	$paginator = Zend_Paginator::factory($select);
    	//ajouter le nombre d'enregistrement par page
    	$paginator->setItemCountPerPage(3);
    	//ajouter la page par defaut
    	$paginator->setCurrentPageNumber($this->_getParam('page', 1));
    	//ajouter le paginateur au view
    	$this->view->paginator = $paginator;
    	 
    	 
    	$headercolums=array(
    			"labelrepense"=>"Reponse",
    			"repensevrai"=> "Reponse juste",
    			"typereponse_idtypereponse"=>"Type de reponse",
    			"score"=>"Score"
    			 
    	);
    	$this->view->headercolums=$headercolums;
    	 
    	Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
    	 
    	//********************************************Ajouter et enregistrer*****************
    	 
    	$reponseform = new Application_Form_Editerreponse();
    	$this->view->form = $reponseform;
    	 
    	
    	 
    	if($this->_request->getParam("idreponse")){
    		$datestamp=new Zend_Date();
    		$model=new Application_Model_DbTable_Reponse();
    		$data=$model->fetchRow('idreponse =' . $this->_request->getParam("idreponse"))->toArray();
    	
    		$datapopulate=array(
    				 
    				'typereponse_idtypereponse'=>$data['typereponse_idtypereponse']
    				,'labelrepense'=>$data['labelrepense']
    				,'textquestion'=> $data['textquestion']
    				,'repensevrai'=>$data['repensevrai']
    				,'score'=>$data['score']
    				,'descriptionhelp'=>$data['descriptionhelp']
    					
    		);
    		$reponseform->populate($datapopulate);
    	}
    	
    	
    	if ($this->_request->isPost()) {
    		$formData = $this->_request->getPost();
    		
    		
    		if ($reponseform->isValid($formData)) {
    			$reponse = new Application_Model_DbTable_Reponse();
    	
    		 
    			
    			
    			$data =array(
    					'Question_idQuestion'=>$this->getRequest()->getParam("id")
    					,'typereponse_idtypereponse'=> $reponseform->getValue('typereponse_idtypereponse')
    					,'labelrepense'=> $reponseform->getValue('labelrepense')
    					,'repensevrai'=> $reponseform->getValue('repensevrai')
    					,'score'=> $reponseform->getValue('score')
    					,'descriptionhelp'=> $reponseform->getValue('descriptionhelp')
    						
    			);
    			if($this->_request->getParam("idreponse")){
    				$reponse->update($data,'idreponse =' . $this->_request->getParam("idreponse"));
    			}else{
    				$reponse->insert($data);
    			}
    				//$reponseform->reset();
    			 
    			 $this->_helper->redirector("editerrepense","gsondage","sondage",array("id"=>$this->getRequest()->getParam("id")));
    		}
    	}
    		 
    	
    }

    public function getresultsAction()
    {
    	// action body
    	
    }

    public function mesgagniantsAction()
    {
        // action body
        
    	$id=$this->_request->getParam("id");
    	$this->view->idsondage=$this->_request->getParam("id");
    	
    	$headercolums=array(
    			"nom"=> "Nom",
    				"prenom"=>"Prenom",
    				"email"=>"E-mail",
    				"titre"=>"Titre Sondage",
    				"scorefinal"=>"Score final",
    				"telephone"=>"téléphone",
					"ETATB" =>  "etablissement",
					'CIN'=> 'CIN'
    	);
    	$this->view->headercolums=$headercolums;
    	
    	
    	$mesgagnants=new Application_Model_Mapper_Lesgagnants();
    	$listgagnant=$mesgagnants->hasGaganant($id);
    	if(count($listgagnant)>0){
    		
    		if(count($listgagnant)<3){
    			
    			
    			
    			$sondage=new Application_Model_Mapper_Sondage();
    			 
    			$result=$sondage->getSondageResult($id);
    			
    			$resval=0;
    			$nbrres=count($listgagnant);
    			$resfinal=array();
    			
    			$resfinal[0]=$listgagnant;
    			
    			$niveau=0;
    			foreach($result as $res){
    				if($resval != $res['scorefinal']){
    					$resval=$res['scorefinal'];
    					$resfinal[++$niveau][]=$res;
    					if($nbrres>=3){
    						break;
    					}
    				}else if($resval==$res['scorefinal']){
    					$resfinal[$niveau][]=$res;
    				}
    				$nbrres++;
    			}
    			 
    			
    			$paginator=array();
    			for($i=0;$i<=$niveau;$i++){
    				if($i==0 && count($resfinal[$i])>3){
    					$indexs=array_rand($resfinal[$i],3);
    					foreach ($indexs as $index){
    						$paginator[]=$resfinal[$i][$index];
    					}
    			
    				}elseif($i==0 && count($resfinal[$i])<=3){
    					$paginator=$resfinal[$i];
    				}
    				elseif($i>0 && (count($resfinal[$i])>=(3-count($paginator)))){
    					if((3-count($paginator)>1)){
    						$indexs=array_rand($resfinal[$i],(3-count($paginator)));
    						foreach ($indexs as $index){
    							$paginator[]=$resfinal[$i][$index];
    						}
    					}elseif((3-count($paginator))==1){
    						$index=array_rand($resfinal[$i],1);
    						$paginator[]=$resfinal[$i][$index];
    					}
    			
    			
    				}elseif($i>0 && (count($resfinal[$i])<(3-count($paginator)))){
    					$paginator = array_merge($paginator,$resfinal[$i]);
    				}
    			}
    			
    			$this->view->paginator = $paginator;
    			if ($this->_request->isPost()) {
    				$formData = $this->_request->getPost();
    				$gagant=new Application_Model_DbTable_Lesgagnants();
    				$gagnantres=explode("_", $formData['gagnants']);
    				foreach($gagnantres as $items){
    					$row = $gagant->createRow();
    					$row->idparticipation=$items;
    					$row->save();
    				}
    			
    				$this->_helper->redirector("gestionsondage");
    			
    			}
    			
    		}else{
    			$paginator = Zend_Paginator::factory($listgagnant);
    			 
    			//ajouter le nombre d'enregistrement par page
    			$paginator->setItemCountPerPage(5);
    			//ajouter la page par defaut
    			$paginator->setCurrentPageNumber($this->_getParam('page', 1));
    			//ajouter le paginateur au view
    			$this->view->paginator = $paginator;
    			
    			Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
    			 
    			
    			if ($this->_request->isPost()) {
    				 
    				$this->_helper->redirector("gestionsondage");
    			
    			}
    		}
    		
    		
    		
    		
    	}else{
    		$sondage=new Application_Model_Mapper_Sondage();
    		 
    		$result=$sondage->getSondageResult($id);
    		
    		$resval=0;
    		$nbrres=0;
    		$resfinal=array();
    		$niveau=-1;
    		foreach($result as $res){
    			if($resval != $res['scorefinal']){
    				$resval=$res['scorefinal'];
    				$resfinal[++$niveau][]=$res;
    				if($nbrres>=3){break;}	
    			}else if($resval==$res['scorefinal']){
    				$resfinal[$niveau][]=$res;
    			}
    		$nbrres++;
    		}
    	
    		
    		$paginator=array();
    		for($i=0;$i<=$niveau;$i++){
	    		if($i==0 && count($resfinal[$i])>3){
	    			$indexs=array_rand($resfinal[$i],3);
	    			foreach ($indexs as $index){
	    				$paginator[]=$resfinal[$i][$index];
	    			}
	    	
	    		}elseif($i==0 && count($resfinal[$i])<=3){
	    			$paginator=$resfinal[$i];
	    		} 		
	    		elseif($i>0 && (count($resfinal[$i])>=(3-count($paginator)))){
	    			if((3-count($paginator)>1)){
	    				$indexs=array_rand($resfinal[$i],(3-count($paginator)));
	    				foreach ($indexs as $index){
	    					$paginator[]=$resfinal[$i][$index];
	    				}
	    			}elseif((3-count($paginator))==1){
	    				$index=array_rand($resfinal[$i],1);
	    				$paginator[]=$resfinal[$i][$index];
	    			}
	    			
	    			
	    		}elseif($i>0 && (count($resfinal[$i])<(3-count($paginator)))){
	    			$paginator = array_merge($paginator,$resfinal[$i]);
	    		}
    		}
    		
    		
    		$this->view->paginator = $paginator;
  		
    		
    		 
    		if ($this->_request->isPost()) {
    			$formData = $this->_request->getPost();
    			$gagant=new Application_Model_DbTable_Lesgagnants();
    			$gagnantres=explode("_", $formData['gagnants']);
    			foreach($gagnantres as $items){
    				$row = $gagant->createRow();
    				$row->idparticipation=$items;
    				$row->save();
    			}
    		
    			$this->_helper->redirector("gestionsondage");
    		
    		}
    	}
   	
    }

    public function listparticipantsAction()
    {
        // action body
    	
    	
    	
    	$id=$this->_request->getParam("id");
    	$mapper=new Application_Model_Mapper_Participation();
    	$select=$mapper->getAllPaticipant($id);
    	$this->view->coutparticipe=count($select);
    	//ajouter le requtte a la paginateur
    	$paginator = Zend_Paginator::factory($select);
    	//ajouter le nombre d'enregistrement par page
    	$paginator->setItemCountPerPage(20);
    	//ajouter la page par defaut
    	$paginator->setCurrentPageNumber($this->_getParam('page', 1));
    	//ajouter le paginateur au view
    	$this->view->paginator = $paginator;
    	 
    	 
    	$headercolums=array(
    			"nom"	=>"Nom",
    			"prenom" =>"Prenom"	,	
    			"email"	 =>"E-mail"	,
    			"telephone"	 =>"Prenom"	,
    			"adresse"	 =>"Adress"	
    			 
    			 
    	);
    	$this->view->headercolums=$headercolums;
    	 
    	Zend_View_Helper_PaginationControl::setDefaultViewPartial('controls.phtml');
    }

	  public function supprimerganantAction()
    {
        // action body
      $this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender(true);
    	$id=$this->_request->getParam("id");
    	 echo "id ".$this->_request->getParam("idsondage");
    	$idsondage=$this->_request->getParam("idsondage");
    	
    	$mesgagnants=new Application_Model_DbTable_Lesgagnants();
    	$mesgagnants->delete ( array ("idgagnants = ?" => $id ) );
    
    	
    	$this->_helper->redirector("mesgagniants","gsondage","sondage",array("id"=>$idsondage));
        
    }
    
    
    public function testjeuxAction()
    {
    	// action body
    
    	$this->_helper->layout()->disableLayout();
    	$this->_helper->layout()->setLayout("reponselayout");
    	 
    	 
    	$identity=Zend_Auth::getInstance()->getIdentity();
    	$idsondage=$this->getRequest()->getParam("id");
    	 
    	$participantdb=new Application_Model_DbTable_Participation();
    	$res=$participantdb->fetchRow("  sondagepersonne_idsondagepersonne = ".$identity->idsondagepersonne." AND sondage_idsondage= $idsondage");
    	 
    	$part=new Application_Model_Mapper_Sondage();
    	$respart=$part->ispasser($identity->idsondagepersonne, $idsondage);
    
    	$reponsesforme=new Application_Form_Mesreponses();
    	$this->view->form=$reponsesforme;
    	 

    	 
    	 
    	 
    	 
    }
    

}



